package com.zhang.novel.controller;

import com.zhang.novel.core.bean.UserDetails;
import com.zhang.novel.core.enums.ResponseStatus;
import com.zhang.novel.core.exception.BusinessException;
import com.zhang.novel.core.utils.ThreadLocalUtil;
import com.zhang.novel.entity.*;
import com.zhang.novel.service.AuthorService;
import com.zhang.novel.service.BookService;
import com.zhang.novel.service.NewsService;
import com.zhang.novel.service.UserService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Api(tags = "页面接口")
@Controller
public class PageController extends BaseController {

    private final BookService bookService;

    private final NewsService newsService;

    private final AuthorService authorService;

    private final UserService userService;

//    @GetMapping("{url}.html")
//    public String module(@PathVariable("url") String url) {
//        return url;
//    }

    @GetMapping("{module}/{url}.html")
    public String module2(@PathVariable("module") String module, @PathVariable("url") String url, HttpServletRequest request) {
        if (request.getRequestURI().startsWith("/author")) {
            // 访问作者专区
            UserDetails user = getUserDetails(request);
            // 判断用户是否登录
            if (null == user) {
                // 未登录
                return "redirect:/user/login.html?originUrl=" + request.getRequestURI();
            }
            // 判断用户是否是作者
            Boolean isAuthor = authorService.isAuthor(user.getId());

            if (!isAuthor) {
                // 不是作者，跳转作者注册页面
                return "redirect:/author/register.html";
            }
        }
        return module + "/" + url;
    }

    /**
     * 首页
     *
     * @return
     */
    @GetMapping(path = {"/", "index", "index.html"})
    public String index() {
        return ThreadLocalUtil.getTemplateDir() + "index";
    }

    /**
     * 作品页
     *
     * @return
     */
    @GetMapping("book/bookclass.html")
    public String bookClass() {
        return "book/bookclass";
    }

    /**
     * 排行页
     *
     * @return
     */
    @GetMapping("book/book_ranking.html")
    public String bookRank() {
        return ThreadLocalUtil.getTemplateDir() + "book/book_ranking";
    }

    /**
     * 详情页
     *
     * @param bookId
     * @param model
     * @return
     */
    @GetMapping("/book/{bookId}.html")
    public String bookDetail(@PathVariable("bookId") Long bookId, Model model) {
        Book book = bookService.queryBookDetail(bookId);
        model.addAttribute("book", book);

        // 查询首页章节ID
        Long firstBookIndexId = bookService.queryFirstBookIndexId(bookId);
        model.addAttribute("firstBookIndexId", firstBookIndexId);

        return ThreadLocalUtil.getTemplateDir() + "book/book_detail";
    }

    /**
     * 目录页
     *
     * @param bookId
     * @param model
     * @return
     */
    @GetMapping("/book/indexList-{bookId}.html")
    public String indexList(@PathVariable("bookId") Long bookId, Model model) {
        Book book = bookService.queryBookDetail(bookId);

        model.addAttribute("book", book);
        List<BookIndex> bookIndexList = bookService.queryIndexList(bookId, null, null);
        model.addAttribute("bookIndexList", bookIndexList);
        model.addAttribute("bookIndexCount", bookIndexList.size());

        return ThreadLocalUtil.getTemplateDir() + "book/book_index";
    }

    /**
     * 内容页
     * @param bookId
     * @param bookIndexId
     * @param request
     * @param model
     * @return
     */
    @GetMapping("/book/{bookId}/{bookIndexId}.html")
    public String indexList(@PathVariable("bookId") Long bookId, @PathVariable("bookIndexId") Long bookIndexId, HttpServletRequest request, Model model) {
        // 查询书籍
        Book book = bookService.queryBookDetail(bookId);
        model.addAttribute("book", book);

        //查询目录
        BookIndex bookIndex = bookService.queryBookIndex(bookIndexId);
        model.addAttribute("bookIndex", bookIndex);

        //查询上一章节目录ID
        Long preBookIndexId = bookService.queryPreBookIndexId(bookId, bookIndex.getIndexNum());
        model.addAttribute("preBookIndexId", preBookIndexId);

        // 查询下一章节目录ID
        Long nextBookIndexId = bookService.queryNextBookIndexId(bookId, bookIndex.getIndexNum());
        model.addAttribute("nextBookIndexId", nextBookIndexId);

        // 查询内容
        BookContent bookContent = bookService.queryBookContent(bookIndex.getId());
        model.addAttribute("bookContent", bookContent);

        // 判断该章节是否收费
        if (null != bookIndex.getIsVip() && 1 == bookIndex.getIsVip()) {
            // 该章节属于VIP章节，判断用户是否购买过该VIP章节
            UserDetails user = getUserDetails(request);

            if (null == user) {
                throw new BusinessException(ResponseStatus.NO_LOGIN);
            }

            Boolean isBuy = userService.queryIsBuyBookIndex(user.getId(), bookIndexId);

            if(!isBuy){
                // 未购买，告知前台用户需要购买
                bookContent.setContent(null);
                model.addAttribute("needBuy",true);
                return "book/book_content";
            }
        }
        // 用户已购买，告知前台用户不需要购买
        model.addAttribute("needBuy",false);
        return ThreadLocalUtil.getTemplateDir()+"book/book_content";
    }

    /**
     * 评论页
     * @param bookId
     * @param model
     * @return
     */
    @GetMapping("/book/comment-{bookId}.html")
    public String commentList(@PathVariable("bookId") Long bookId,Model model){
        // todo: 不明白评论页是查询书籍详情
        //查询书籍
        Book book = bookService.queryBookDetail(bookId);
        model.addAttribute("book",book);
        return "book/book_comment";
    }

    /**
     * 新闻内容页面
     * @param newsId
     * @param model
     * @return
     */
    @GetMapping("/about/newsInfo-{newsId}.html")
    public String newsInfo(@PathVariable("newsId") Long newsId,Model model){
        // 查询新闻
        News news=newsService.queryNewsInfo(newsId);
        model.addAttribute("news",news);

        return "about/news_info";
    }

    @PostMapping("author/register.html")
    public String authorRegister(Author author,HttpServletRequest request, Model model){
        UserDetails user = getUserDetails(request);

        if(null == user){
            return "redirect:/user/login.html?originUrl=/author/register.html";
        }

        if(StringUtils.isNotBlank(author.getInviteCode())){
            // 提交作者注册信息
            String errorInfo = authorService.register(user.getId(), author);

            if(StringUtils.isBlank(errorInfo)){
                return "redirect:/author/index.html";
            }
            model.addAttribute("LabErr",errorInfo);
            model.addAttribute("author",author);
        }

        return "author/register";
    }
}
